/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import beans.InfoSyncStorage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import sun.misc.BASE64Encoder;

/**
 *
 * @author pascal
 */
public class Acces extends HttpServlet {

    /**
     * Processes requests for HTTP
     * <code>GET</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response, JSONObject liste, InfoSyncStorage store)
            throws ServletException, IOException, JSONException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Acces</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Informations de " + store.getUsername() + "</h1>");

            /*
             * flickr.photos.search
             */
            out.println("<p>Images Public (ne nécéssite pas le token acces)<p>");
            JSONArray array = liste.getJSONObject("photos").getJSONArray("photo");
            for (int i = 0; i < array.length(); i++) {
                int farm = array.getJSONObject(i).getInt("farm");
                String idPhoto = array.getJSONObject(i).getString("id");
                String serverId = array.getJSONObject(i).getString("server");
                String secret = array.getJSONObject(i).getString("secret");
                out.println("<img src=\"http://farm" + farm + ".staticflickr.com/" + serverId + "/" + idPhoto + "_" + secret + "_q.jpg\" />");
            }


            /*
             * flickr.people.getPhotos
             */
            String serverUrl = "http://api.flickr.com/services/rest/?method=flickr.people.getPhotos";
            String api_key = "&api_key=" + store.getAppKey();
            String user_id = "&user_id=" + store.getUserid();
            String oauth_token_secret = "&oauth_token_secret" + store.getTokenAcces();

            /*
             * TODO Trouver les bon paramètres
             */

            String queryToServer =
                    serverUrl
                    + api_key
                    + oauth_token_secret
                    + user_id;

            out.println("<a href=\"" + queryToServer + "\">Lien</a>");

            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    /**
     * Processes requests for HTTP
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /*
             * TODO output your page here. You may use following sample code.
             */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Acces</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Acces at " + request.getContextPath() + "</h1>");
            out.println("<p>Passage en post WTF ???<p>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        InfoSyncStorage store = new InfoSyncStorage();
        String verifier = request.getParameter("oauth_verifier");
        store.setVerifier(verifier);
        Random rand = new Random();
        int nomus = rand.nextInt(99999999);

        long time = System.currentTimeMillis();
        time = time / 1000;
        time = time - 10;


        String requete = "GET&http%3A%2F%2Fwww.flickr.com%2Fservices%2Foauth%2Faccess_token"
                + "&oauth_consumer_key%3D" + store.getAppKey()
                + "%26oauth_nonce%3D" + nomus
                + "%26oauth_signature_method%3DHMAC-SHA1"
                + "%26oauth_timestamp%3D" + time
                + "%26oauth_token%3D" + store.getTokenRequest()
                + "%26oauth_verifier%3D" + store.getVerifier()
                + "%26oauth_version%3D1.0";
        String key = store.getAppSecret() + "&" + store.getTokenSecret();
        SecretKeySpec keySpec = new SecretKeySpec(
                key.getBytes(),
                "HmacSHA1");

        Mac mac = null;
        try {
            mac = Mac.getInstance("HmacSHA1");
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(Acces.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            mac.init(keySpec);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(Acces.class.getName()).log(Level.SEVERE, null, ex);
        }
        byte[] result = mac.doFinal(requete.getBytes());

        BASE64Encoder encoder = new BASE64Encoder();
        String sig = encoder.encode(result);
        System.out.println(sig);

        String lien = "http://www.flickr.com/services/oauth/access_token"
                + "?oauth_nonce=" + nomus
                + "&oauth_timestamp=" + time
                + "&oauth_verifier=" + store.getVerifier()
                + "&oauth_consumer_key=" + store.getAppKey()
                + "&oauth_signature_method=HMAC-SHA1"
                + "&oauth_version=1.0"
                + "&oauth_token=" + store.getTokenRequest()
                + "&oauth_signature=" + sig;

        String info = "";
        String inputLine;

        if (store.getTokenAcces().isEmpty()) {

            URL oracle = new URL(lien);
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(oracle.openStream()));



            while ((inputLine = in.readLine()) != null) {
                info += inputLine;
            }
            in.close();

            String[] infos = info.split("&");
            String fullname = "";
            try {
                fullname = infos[0].split("=")[1];
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("Pas de user fullname");
            }
            String tokenAcces = infos[2].split("=")[1];
            store.setTokenAcces(tokenAcces);
            String tokenSecret = infos[1].split("=")[1];
            store.setTokenSecret(tokenSecret);
            String userId = infos[3].split("=")[1];
            store.setUserid(userId);
            String userName = infos[4].split("=")[1];
            store.setUsername(userName);
            System.out.println(fullname + " " + tokenAcces + " " + tokenSecret + " " + userId + " " + userName);
        }

        /*
         * Demande des photos de l'utilisateur
         */
        /*
         *
         */
        String serverUrl = "http://api.flickr.com/services/rest/?method=flickr.photos.search";
        String photosPerPage = "&per_page=10"; //specify how may photos you want per page  
        String nojsoncallback = "&nojsoncallback=1";
        String responce_format = "&format=json"; // response format from server  
        String user_id = "&user_id=" + store.getUserid();
        String flickrApiKey = "&api_key=" + store.getAppKey(); // replace with your own flicker api key  

        String queryToServer =
                serverUrl
                + photosPerPage
                + nojsoncallback
                + responce_format
                + user_id + flickrApiKey;



        URL askPhoto = new URL(queryToServer);
        BufferedReader in2 = new BufferedReader(
                new InputStreamReader(askPhoto.openStream()));

        info = "";
        inputLine = "";
        while ((inputLine = in2.readLine()) != null) {
            info += inputLine;
        }
        in2.close();


        JSONObject liste = new JSONObject();
        try {
            liste = new JSONObject(info);
            System.out.print(liste);




            processRequest(request, response, liste, store);
        } catch (JSONException ex) {
            Logger.getLogger(Acces.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
